package com.atguigu.gmall.list.service.impl;


import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.list.repository.GoodsRepository;
import com.atguigu.gmall.list.service.SearchService;
import com.atguigu.gmall.model.list.*;
import com.atguigu.gmall.model.product.BaseAttrInfo;
import com.atguigu.gmall.model.product.BaseCategoryView;
import com.atguigu.gmall.model.product.BaseTrademark;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Repository
public class SearchServiceImpl implements SearchService {
    // 远程调用 然后将查询到的数据放入es 中去  需要借助Goods实体类！
    @Autowired
    private ProductFeignClient productFeignClient;

    //GoodsRepository继承了repository封装了save等方法 类似以IService  IServiceImplement
    @Autowired
    private GoodsRepository goodsRepository;
    //实现多多线程任务执行
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RestHighLevelClient client;

    @Override
    public void upperGoods(Long skuId) {
        //创建一个Goods
        Goods goods = new Goods();
        //给goods赋值
        // 利用多线程进行封装
        CompletableFuture<SkuInfo> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            // 1、      获取品牌数据
            SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
            goods.setId(skuInfo.getId());
            goods.setTitle(skuInfo.getSkuName());
            goods.setDefaultImg(skuInfo.getSkuDefaultImg());
            goods.setPrice(skuInfo.getPrice().doubleValue());
            goods.setCreateTime(new Date());
            return skuInfo;
        }, threadPoolExecutor);
        //  2、  获取品牌数据
        CompletableFuture<Void> trademarkFuture = skuInfoFuture.thenAcceptAsync((skuInfo) -> {
            BaseTrademark trademark = productFeignClient.getTrademark(skuInfo.getTmId());
            goods.setTmId(trademark.getId());
            goods.setTmName(trademark.getTmName());
            goods.setTmLogoUrl(trademark.getLogoUrl());
        }, threadPoolExecutor);
        //  3、 获取分类数据
        CompletableFuture<Void> categoryViewFuture = skuInfoFuture.thenAcceptAsync((skuInfo) -> {
            BaseCategoryView categoryView = productFeignClient.getCategoryView(skuInfo.getCategory3Id());
            goods.setCategory1Id(categoryView.getCategory1Id());
            goods.setCategory2Id(categoryView.getCategory2Id());
            goods.setCategory3Id(categoryView.getCategory3Id());

            goods.setCategory1Name(categoryView.getCategory1Name());
            goods.setCategory2Name(categoryView.getCategory2Name());
            goods.setCategory3Name(categoryView.getCategory3Name());
        }, threadPoolExecutor);
        // 4、  获取平台属性  无返回值
        CompletableFuture<Void> attrListFuture = CompletableFuture.runAsync(() -> {
            List<BaseAttrInfo> attrList = productFeignClient.getAttrList(skuId);
//            private List<SearchAttr> attrs;
            List<SearchAttr> attrs = attrList.stream().map(baseAttrInfo -> {
                SearchAttr searchAttr = new SearchAttr();
                searchAttr.setAttrId(baseAttrInfo.getId());
                searchAttr.setAttrName(baseAttrInfo.getAttrName());
                searchAttr.setAttrValue(baseAttrInfo.getAttrValueList().get(0).getValueName());
                return searchAttr;
            }).collect(Collectors.toList());
            goods.setAttrs(attrs);
        }, threadPoolExecutor);

        //   多任务组合
        CompletableFuture.allOf(
                skuInfoFuture,
                trademarkFuture,
                categoryViewFuture,
                attrListFuture

        ).join();
        this.goodsRepository.save(goods);
    }

    @Override
    public void lowerGoods(Long skuId) {
        //  删除数据
        this.goodsRepository.deleteById(skuId);
    }

    @Override
    public void incrHotScore(Long skuId) {
//定义一个key
        String hotKey = "hotScore:";
        Double count = redisTemplate.opsForZSet().incrementScore(hotKey, "skuId:" + skuId, 1);
        if (count % 3 == 0) {//每查询3次往es中存一次
//        更新es
            Optional<Goods> optional = goodsRepository.findById(skuId);
            Goods goods = optional.get();
            goods.setHotScore(count.longValue());
            goodsRepository.save(goods);
        }

    }

    //    先通过 网关gateway==>web all==>远程调用serviceList==>json转为object
    @Override
    public SearchResponseVo search(SearchParam searchParam) throws IOException {
        /*
            1、生成dsl
            2、执行dsl语句
            3、获取结果数据并转换成SearchResponseVo对象
        */
//        //查询请求对象
//        SearchRequest searchRequest = new SearchRequest();
//        //相当于dsl语句中{}  创建查询器{}
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        //相当于dsl中的  {query}
//        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//        searchRequest.source(searchSourceBuilder);
        //调用高级客户端
        //1、声明一个查询对象，在这个对象中有生成的DSL语句
        SearchRequest searchRequest = this.searchDslBuild(searchParam);
        //2、调用高级客户端
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        //3、声明一个响应对象 返回SearchResponseVo
        SearchResponseVo searchResponseVo = this.parseResultSearchResponse(searchResponse);
        /* SearchResponseVo实体类中属性
    private List<SearchResponseTmVo> trademarkList;
    private List<SearchResponseAttrVo> attrsList = new ArrayList<>();
    private List<Goods> goodsList = new ArrayList<>();
    private Long total;//总记录数 searchResponseVo.setTotal(searchResponse.getHits().getTotalHits().value);
    private Integer pageSize;//每页显示的内容
    private Integer pageNo;//当前页面
    private Long totalPages;*/
        //给总记录数赋值
        long value = searchResponse.getHits().getTotalHits().value;
        searchResponseVo.setTotal(value);
        //给页数赋值  from 起始页下标 size 每页显示条数
        searchResponseVo.setPageNo(searchParam.getPageNo());
        searchResponseVo.setPageSize(searchParam.getPageSize());
        //totalPages总页数   (总记录数+ 每页显示条数-1)/每页显示条数 10 3 4
        Long totalPages = (searchResponseVo.getTotal() + searchParam.getPageSize() - 1) / searchParam.getPageSize();
        searchResponseVo.setTotalPages(totalPages);
        //返回数据
        return searchResponseVo;
    }

    //此方法返回所有结果集
    private SearchResponseVo parseResultSearchResponse(SearchResponse searchResponse) {
        //声明对象
        SearchResponseVo searchResponseVo = new SearchResponseVo();
      //制作返回结果集
        SearchHits hits = searchResponse.getHits();
        //  获取到总记录数！
        searchResponseVo.setTotal(hits.getTotalHits().value);
        //  商品集合数据来自于：
        SearchHit[] subHits = hits.getHits();
        //  循环遍历
        List<Goods> goodsList = new ArrayList<>();
        for (SearchHit subHit : subHits) {
            String sourceAsString = subHit.getSourceAsString();
            //  sourceAsString JSON 变为Goods
            Goods goods = JSON.parseObject(sourceAsString, Goods.class);
            //  不够优秀： 分类Id 不需要高亮， 关键词 需要高亮！
            if(subHit.getHighlightFields().get("title")!=null){
                //  需要高亮：
                Text title = subHit.getHighlightFields().get("title").getFragments()[0];
                goods.setTitle(title.toString());
            }
            //  将商品添加到集合
            goodsList.add(goods);
        }
        //  赋值商品集合数据
        searchResponseVo.setGoodsList(goodsList);

        //  从聚合中获取品牌数据：
        //  Aggregation 变为了map 集合
        Map<String, Aggregation> stringAggregationMap = searchResponse.getAggregations().asMap();
        //  tmId ---> Long 数据类型存储！
        //  Aggregation ---> ParsedLongTerms 目的获取到桶！
        ParsedLongTerms tmIdAgg = (ParsedLongTerms) stringAggregationMap.get("tmIdAgg");
        List<SearchResponseTmVo> trademarkList = tmIdAgg.getBuckets().stream().map(bucket -> {
            //  声明对象
            SearchResponseTmVo searchResponseTmVo = new SearchResponseTmVo();
            String keyAsString = ((Terms.Bucket) bucket).getKeyAsString();
            //  赋值品牌Id
            searchResponseTmVo.setTmId(Long.parseLong(keyAsString));
            //  赋值品牌tmName , 需要先获取tmNameAgg   //  Aggregation ---> ParsedStringTerms 目的获取到桶！
            ParsedStringTerms tmNameAgg = ((Terms.Bucket) bucket).getAggregations().get("tmNameAgg");
            String tmName = tmNameAgg.getBuckets().get(0).getKeyAsString();
            searchResponseTmVo.setTmName(tmName);

            //  赋值品牌tmLogoUrl
            ParsedStringTerms tmLogoUrlAgg = ((Terms.Bucket) bucket).getAggregations().get("tmLogoUrlAgg");
            String tmLogoUrl = tmLogoUrlAgg.getBuckets().get(0).getKeyAsString();
            searchResponseTmVo.setTmLogoUrl(tmLogoUrl);
            return searchResponseTmVo;
        }).collect(Collectors.toList());
        //  给品牌赋值：
        searchResponseVo.setTrademarkList(trademarkList);

        //  从聚合中获取数据：
        //  平台属性值 聚合 nested 需要获取到 attrs
        ParsedNested attrAgg = (ParsedNested) stringAggregationMap.get("attrAgg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attrIdAgg");

        List<SearchResponseAttrVo> attrsList = attrIdAgg.getBuckets().stream().map(bucket -> {
            SearchResponseAttrVo searchResponseAttrVo = new SearchResponseAttrVo();
            //  Number keyAsNumber = ((Terms.Bucket) bucket).getKeyAsNumber();
            String keyAsString = ((Terms.Bucket) bucket).getKeyAsString();
            //  赋值平台属性Id
            searchResponseAttrVo.setAttrId(Long.parseLong(keyAsString));
            //  赋值平台属性名
            ParsedStringTerms attrNameAgg = ((Terms.Bucket) bucket).getAggregations().get("attrNameAgg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            searchResponseAttrVo.setAttrName(attrName);

            //  赋值平台属性值名称
//            List<String> valueNameList = new ArrayList<>();
            ParsedStringTerms attrValueAgg = ((Terms.Bucket) bucket).getAggregations().get("attrValueAgg");
//            for (Terms.Bucket attrValueAggBucket : attrValueAgg.getBuckets()) {
//                String valueName = attrValueAggBucket.getKeyAsString();
//                valueNameList.add(valueName);
//            }
            //  使用拉姆达表达式：
            List<String> valueNameList = attrValueAgg.getBuckets().stream().map(Terms.Bucket::getKeyAsString).collect(Collectors.toList());

            //  赋值平台属性值名称
            searchResponseAttrVo.setAttrValueList(valueNameList);

            return searchResponseAttrVo;
        }).collect(Collectors.toList());

        //  给平台属性赋值：
        searchResponseVo.setAttrsList(attrsList);

        return searchResponseVo;
    }

    //此方法封装所有的DSL语句
    private SearchRequest searchDslBuild(SearchParam searchParam) {
//一、query查询
        //1、创建查询器
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //2、构建boolQuery 判断查询  最外层的
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //3、判断用户是否用关键字查询 关键字 {query--bool----must----match}
        if (!StringUtils.isEmpty(searchParam.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("title", searchParam.getKeyword()).operator(Operator.OR));
        }
        //4、判断用户是否通过category3Id进行查询  {query ----bool---filter--term}
        if (!StringUtils.isEmpty(searchParam.getCategory3Id())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category3Id", searchParam.getCategory3Id()));
        }
        if (!StringUtils.isEmpty(searchParam.getCategory2Id())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category2Id", searchParam.getCategory2Id()));
        }
        if (!StringUtils.isEmpty(searchParam.getCategory1Id())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category1Id", searchParam.getCategory1Id()));
        }
        //5、判断用户是否用品牌id查询
        String trademark = searchParam.getTrademark();
        if (!StringUtils.isEmpty(trademark)) {
            // trademark=2:华为  数组分隔
            String[] split = trademark.split(":");
            if (split != null && split.length == 2) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("tmId", split[0]));
            }
        }
        //6、判断用户是否通过平台属性查询  23:4G:运行内存
        String[] props = searchParam.getProps();
        if (props != null && props.length > 0) {
            for (String prop : props) {
                String[] split = prop.split(":");
                if (split != null && split.length == 3) {
                    // 构建嵌套查询    第二层的bool
                    BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
                    // 嵌套查询子查询  第三层的bool
                    BoolQueryBuilder subBoolQuery = QueryBuilders.boolQuery();

                    subBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", split[0]));
                    subBoolQuery.must(QueryBuilders.termQuery("attrs.attrValue", split[1]));
                    boolQuery.must(QueryBuilders.nestedQuery("attrs", subBoolQuery, ScoreMode.None));
                    //最外层 第一层的bool      1boolQueryBuilder <----2boolQuery <-----3subQuery
                    boolQueryBuilder.filter(boolQuery);
                }
            }
        }
        //执行查询方法 将所有的添加收集
        searchSourceBuilder.query(boolQueryBuilder);
//二、sort排序
        // 7、排序规则 1:hotScore 2:price   order2:asc order2:desc
        String order = searchParam.getOrder();
        if (!StringUtils.isEmpty(order)) {
            String[] split = order.split("：");
            if (split != null && split.length == 2) {
                String field = null;
                switch (split[0]) {
                    case "1":
                        field = "hotScore";
                        break;
                    case "2":
                        field = "price";
                        break;
                }
                //asc==split[1] 就是升序反之降序
                searchSourceBuilder.sort(field, "asc".equals(split[1]) ? SortOrder.ASC : SortOrder.DESC);
            } else {
                //没有传值给默认值
                searchSourceBuilder.sort("hotScore", SortOrder.DESC);
            }

        }

//三、构建 高亮查询
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style=color:red>");
        highlightBuilder.postTags("</span>");

//四、from --size-- 分页   分页当前页的起始索引=(当前页-1)*每页显示条数
        int from = (searchParam.getPageNo() - 1) * searchParam.getPageSize();
        searchSourceBuilder.from(from);
        //每页显示条数
        searchSourceBuilder.size(searchParam.getPageSize());

//五、聚合查询Aggeration品牌
        searchSourceBuilder.aggregation(AggregationBuilders.terms("tmIdAgg").field("tmId")
                .subAggregation(AggregationBuilders.terms("tmNameAgg").field("tmName"))
                .subAggregation(AggregationBuilders.terms("tmLogoUrlAgg").field("tmLogoUrl"))
        );
        //设置平台属性聚合
        searchSourceBuilder.aggregation(AggregationBuilders.nested("attrAgg","attrs")
                .subAggregation(AggregationBuilders.terms("attrIdAgg").field("attrs.attrId")
                        .subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName"))
                        .subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue"))
                        ));

        //结果集过滤
        searchSourceBuilder.fetchSource(new String[]{"id","defaultImg","title","price"},null);
        SearchRequest request = new SearchRequest("goods");
        request.source(searchSourceBuilder);
        System.out.println("DSL语句:" + searchSourceBuilder.toString());
        return request;
        //制作返回结果集 hit在上面....
    }
}
